<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled ">
      <template #detail>
        <a-form v-bind="formItemLayout">
          <a-row>
            <a-col :lg="12"  v-auth="'packaging:purchase'">
              <a-form-item v-bind="validateInfos.factoryId" label="工厂" >
                <j-search-select :disabled="addDisabled" placeholder="请选择工厂" v-model:value="formData.factoryId" dict="p_factory_manage,name,code" allow-clear />
              </a-form-item>
            </a-col>
						<a-col :span="12">
              <a-form-item label="包材名称" v-bind="validateInfos.name" >
                <a-input placeholder="请输入名称" v-model:value="formData.name" allow-clear ></a-input>
              </a-form-item>
						</a-col>
						<a-col :span="12">
              <a-form-item label="库存" v-bind="validateInfos.stock" >
                <a-input-number :disabled="addDisabled"  v-model:value="formData.stock" placeholder="请输入库存" :precision="2"  style="width: 100%" />
              </a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="单位" v-bind="validateInfos.unit">
                <j-search-select v-model:value="formData.unit" dict="unit_code"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="图片" v-bind="validateInfos.img">
                <JImageUpload :fileMax="2" v-model:value="formData.img"></JImageUpload>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="包材绑定的产品" key="packagingProductRelation" :forceRender="true">
        <JVxeTable
          :keep-source="true"
          resizable
          ref="packagingProductRelationTableRef"
          :loading="packagingProductRelationTable.loading"
          :columns="packagingProductRelationTable.columns"
          :dataSource="packagingProductRelationTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          authPre="packaging"
          @valueChange="handleValueChange"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
import {defineComponent, ref, reactive, computed, toRaw, onMounted, watch, watchEffect} from 'vue';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryPackagingProductRelationListByMainId, queryDataById, saveOrUpdate } from '../PackagingDetails.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import {packagingProductRelationColumns} from '../PackagingNewProduct.data';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form } from 'ant-design-vue';
import {JVxeLinkageConfig, JVxeTypes} from "@/components/jeecg/JVxeTable/src/types";
import {initDictOptions} from "@/utils/dict";

import { usePermission } from '/@/hooks/web/usePermission';
const { hasPermission } = usePermission();
import { defHttp } from '/@/utils/http/axios';
const useForm = Form.useForm;
import { useUserStore } from '/@/store/modules/user';
import JImageUpload from "@/components/Form/src/jeecg/components/JImageUpload.vue";
const userStore = useUserStore();

  export default defineComponent({
    name: "PackagingProductForm",
    components:{
      JImageUpload,
      JSearchSelect,
      JVxeTable,
			JFormContainer,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {

      const loading = ref(false);
      const packagingProductRelationTableRef = ref();

      // if (hasPermission('packaging:purchase')) {
        const packagingProductRelationTable = reactive<Record<string, any>>({
          loading: false,
          columns: packagingProductRelationColumns,
          dataSource: []
        });
      // }else if (hasPermission('packaging:factory')) {
      //
      // }

      const activeKey = ref('packagingProductRelation');
      const formData = reactive<Record<string, any>>({
        id: '',
        name: '',
        stock: '',
        unit:'',
        factoryId:'',
        img:''
      });

      //表单验证
      const validatorRules = reactive({
        factoryId:[{required: true, message: '请选择工厂名称!'}],
        name: [{ required: true, message: '请输入包材名称!'},],
        stock: [{ required: true, message: '请输入库存!'},],
        unit:[{required: true, message: '请选择单位!'}]
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };



      // const specCodeDict = ref(`goods_info_spec,spec_no,spec_no`);

      const  dictOptions = ref ([]);

      // 加载字典数据
      const fetchDictOptions =  async (factoryId) => {
        loading.value = true; // 开始加载
        let url = '/packaging/factoryProduct/dict'
        if (factoryId) {
          url = '/packaging/factoryProduct/dict?factoryId='+factoryId
        }
        try {
          // 使用 await 等待异步操作完成
          const res = await defHttp.get({ url: url });
          loading.value = false; // 加载结束

          if (res && res.length > 0) {
            dictOptions.value = res.map((item) => ({
              text: item.goodsName,
              value: item.goodsNo,
            }));
          } else {
            dictOptions.value = [];
          }
          packagingProductRelationTable.columns[0].options = dictOptions.value

          // 更新列的配置
          // packagingProductRelationColumns[0] = {
          //   title: '产品1',
          //   key: 'goodsNo',
          //   type: JVxeTypes.selectSearch,
          //   width: "450px",
          //   options: dictOptions.value,
          //   validateRules: [
          //     { required: true, message: '${title}不能1为空' },
          //   ],
          // };
          console.log(packagingProductRelationColumns[0]);
        } catch (error) {
          loading.value = false; // 加载失败
          console.error('加载字典数据失败:', error);
          dictOptions.value = [{ text: '加载失败', value: '' }];
          packagingProductRelationColumns[0].options = [];
        }


      };

      watch(() => formData.factoryId, async (newFactoryId) => {
        console.log(newFactoryId)
        await fetchDictOptions(newFactoryId)
        // packagingProductRelationTable.columns[0].options = dictOptions.value
        console.log('列配置更新后:', packagingProductRelationTable.columns);
        packagingProductRelationTable.columns = [...packagingProductRelationTable.columns];
        packagingProductRelationTable.dataSource = [...packagingProductRelationTable.dataSource];
        //

      });

      // // 监听 dataSource 中的包装产品的 packagingId 变化，并设置 unit 值
      // watch(() => packagingProductRelationTable.columns, (newDataSource) => {
      //   console.log(newDataSource)
      //   console.log("-----------------")
      //   newDataSource.forEach((row) => {
      //       row.unit = formData.unit;
      //   });
      // }, { immediate: true });
      const addDisabled = ref(false)
      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

     async function add() {
        if(userStore.getUserInfo.factoryId) {
          validatorRules.factoryId[0].required = false
        }
        addDisabled.value = false
        resetFields();
        await fetchDictOptions(null);
        packagingProductRelationTable.dataSource = [];
      }

      function handleValueChange(event) {
        console.log('handleValueChange.event: ', event);
        console.log('handleValueChange.event: ', event.row);
        if (event.cellType = "select-search") {
          event.row.unit = formData.unit
          // const dictData = initDictOptions('p_packaging,unit,unit,'+ encodeURIComponent(`id = '${event.row.packagingId}'`))
          // dictData.then(res=>{
          //   console.log(res[0])
          //   if (res[0]) {
          //     event.row.unit = res[0].text
          //   }else {
          //     event.row.unit = ''
          //   }
          // })
        }


      }


      async function edit(row) {
        addDisabled.value = true

        await fetchDictOptions(row.factoryId);
        //主表数据
        await queryMainData(row.id);


        //子表数据
        const packagingProductRelationDataList = await queryPackagingProductRelationListByMainId(row.id,row.factoryId);

        packagingProductRelationDataList.forEach(e => {
          // e.purchase = e.goodsNo
          // e.factory = e.goodsNo
          if (hasPermission('packaging:purchase')) {
            e.goodsNo = e.goodsNo
          }else if (hasPermission('packaging:factory')) {
            e.goodsNo = e.goodsNo
          }
        })
        console.log(packagingProductRelationDataList)

        packagingProductRelationTable.columns = [...packagingProductRelationTable.columns];
        // packagingProductRelationTable.dataSource = [...packagingProductRelationTable.dataSource];
        packagingProductRelationTable.dataSource = [...packagingProductRelationDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }

        })
        //赋值
        Object.assign(formData,tmpData);

      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'packagingProductRelation': packagingProductRelationTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }

      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      // // 在组件挂载时加载数据
      // onMounted(() => {
      //
      // });



      return {
        handleValueChange,
        packagingProductRelationTableRef,
        packagingProductRelationTable,
        validatorRules,
        validateInfos,
        activeKey,
        // specCodeDict,
        dictOptions,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        addDisabled,
        getFormData,
        submitForm,
        add,
        edit,
        fetchDictOptions,
      }
    }
  });
</script>
<style lang="less" scoped></style>
